/// 全局状态 * 登录信息

import { defineStore } from 'pinia'
import { isEmpty } from 'xe-utils'
import { cache } from '@/helpers'
import { apiMergeLoginProject, apiQueryLoginProjects } from '@/apis/Login'

export const useLoginStore = defineStore('login', () => {
  const info = computed(() => cache.getLoginInfo())

  const user = computed(() => ({
    id: info.value?.id,
    name: info.value?.userName,
    realName: info.value?.realName,
    status: info.value?.userStatus,
  }))

  const role = computed(() => ({
    id: info.value?.roleId,
    name: info.value?.roleName,
  }))

  const project = useSelecty({
    codes: ['id', 'projectName'],
    sourcePick: true,
  })

  const resetProject = () => {
    project.value = void 0
    project.options = null as any
  }
  {
    resetProject()
  }

  const loadProject = async () => {
    if (isEmpty(project.options)) {
      let data: any = []
      try {
        data = await apiQueryLoginProjects()
      }
      catch {}
      setOptions(project, data)
    }
    if (project.value == null) {
      project.value = cache.getLoginInfo()?.lastProjectId ?? project.options[0]?.value
      if (!getOption(project)) {
        project.value = project.options[0]?.value
      }
    }
    if (project.value != null && project.value != cache.getLoginInfo()?.lastProjectId) {
      await apiMergeLoginProject(project.value)
    }
  }

  const renewProject = async () => {
    if (project.value != null) {
      await apiMergeLoginProject(project.value)
    }
  }

  return {
    info,
    user,
    role,
    project,
    loadProject,
    resetProject,
    renewProject,
  }
})
